package com.example.demo.utils;

import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;

import java.security.SecureRandom;

public class Sm4Util extends Sm4SgEcb {
    public static final String KEY = "294febe695f9f1695bf8b9c12348779f";
    private static Sm4Util sm4UtilLS = null;

    public static Sm4Util getInstance() {
        if (sm4UtilLS == null)
            synchronized (Object.class) {
                if (sm4UtilLS == null)
                    sm4UtilLS = new Sm4Util();
            }
        return sm4UtilLS;
    }

    /**
     * generate a secret key.
     *
     * @return a random key or iv with hex code type.
     */
    public String generateKeyOrIV() {
        byte[] key = new byte[16];
        new SecureRandom().nextBytes(key);
        return org.postgresql.shaded.com.ongres.scram.common.bouncycastle.pbkdf2.Strings.fromByteArray(Hex.encode(key));
    }

    /**
     * 使用国密SM4算法ECB模式进行加密数据
     *
     * @param plainText 需要加密的明文数据
     * @param key       加密需要的hex编码的秘钥
     * @return 返回加密后的hex编码的密文
     */
    public final String encryptBySM4ECB(String plainText, String key) {
        //调用国密SM4算法的ecb模式对明文数据进行加密
        byte[] sg_EncECBData = SG_EncECBData(Hex.decode(key), Strings.toUTF8ByteArray(plainText.toCharArray()));
        return org.postgresql.shaded.com.ongres.scram.common.bouncycastle.pbkdf2.Strings.fromByteArray(Hex.encode(sg_EncECBData));
    }


    /**
     * 使用国密	SM4算法ECB模式进行解密数据
     *
     * @param cipherText 需要进行解密hex编码密文
     * @param key        解密需要的hex编码的秘钥
     * @return 返回解密后的明文信息
     */
    public final String decryptBySM4ECB(String cipherText, String key) {
        //调用国密SM4算法ECB模式对密文进行解密
        byte[] sg_EncECBData = SG_DecECBData(Hex.decode(key), Hex.decode(cipherText));
        return Strings.fromUTF8ByteArray(sg_EncECBData);
    }
}
